(function() {
	var $ = require(L('$')), _ = require(L('_'));

	var win = $.createWindow(L('win_notifications'), true);
	var ui = $.layout('notifications/view');
	ui.top.add($.ui('partial').scan_and_take_photo());
	win.nav.window.add([$.ui('navbar')(false, true), ui.view]);
	win.display = function() {
		$.opacity_show(ui.view, false);
		$.mask();
		$.webservice().getNotifications(function(responseText, nothingNew) {
			$.mask(false);
			if (nothingNew && ui.table.isBuilt) {
				$.opacity_show(ui.view);
				return;
			}
			var result = JSON.parse(responseText);
			if (!nothingNew && result) {
				$.badgeNotification(result.UnreadNumber);
				$.ui('bottom').update_badge();
			}
			ui.table.render(result);
			$.opacity_show(ui.view);
		});
	};

	ui.table.render = function(data) {
		var tableData = new Array();
		_.each(data.NotificationItems, function(item) {
			$.i('NOTIFICATION : ' + item.NotificationID);
			tableData.push(ui.table.one_row(item));
		});
		tableData.push($.ui('partial').empty_row());
		ui.table.data = tableData;
		ui.table.isBuilt = true;
		ui.table.scrollToTop(0);
	};
	ui.table.one_row = function(item) {
		var pui = $.layout('notifications/row');
		pui.row.notificationID = item.NotificationID;
		pui.row.selectionStyle = Ti.UI.iPhone.TableViewCellSelectionStyle.NONE;
		$.cache_image(item.BannerLinkImage, null, function(e) {
			var blobImage = Ti.UI.createImageView({
				image : e
			}).toImage();
			pui.image.image = e;
			var height = blobImage.height * 320 / blobImage.width;
			pui.row.height = height;
			pui.image.height = height;
		});
		$.on('load', pui.image, function() {
			// pui.container.remove(pui.loading);
			pui.loading.visible = false;
		});
		return pui.row;
	};
	$.click(ui.table, function(e) {
		if (e && e.row && e.row.notificationID) {
			$.win('notification_details').display(e.row.notificationID);
			$.win('notifications').nav.push($.win('notification_details'));
		}
	});
	$.on('delete', ui.table, function(e) {
		if (e && e.row && e.row.notificationID)
			$.webservice().deleteNotifications([e.row.notificationID], function(e) {
				var result = JSON.parse(e);
				if (result && result.UnreadNotificationNumber) {
					$.badgeNotification(result.UnreadNumber);
					$.ui('bottom').update_badge();
				}
			});
	});
	module.exports = win;
})();
